package com.niiwoo.civet.trade.service.local.newRefund.notify.dubbo;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.base.enums.RefundOrderStatusEnum;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectBorrowerSummary;
import com.niiwoo.civet.trade.dao.entity.RefundNotifyRecord;
import com.niiwoo.civet.trade.dao.entity.RefundOrder;
import com.niiwoo.civet.trade.dao.mapper.ProjectBorrowerSummaryMapper;
import com.niiwoo.civet.trade.enums.NotifyTypeEnum;
import com.niiwoo.civet.trade.enums.ProjectFromSourceEnum;
import com.niiwoo.civet.trade.enums.ProjectTypeEnum;
import com.niiwoo.civet.trade.enums.RefundTradeTypeEnum;
import com.niiwoo.civet.trade.enums.RepayStatusEnum;
import com.niiwoo.civet.trade.service.local.newRefund.notify.RefundNotifyHandle;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyDTO;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyHandleResult;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyMessageDTO;
import com.niiwoo.civet.trade.service.local.newRefund.notify.enums.RefundNotifyEnum;
import com.niiwoo.civet.trade.service.local.notify.Notifiers;
import com.niiwoo.tripod.tiancheng.component.TianChengRefundEventService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class MessageBorrowerRefundNotify implements RefundNotifyHandle {

	@Autowired
	private ProjectBorrowerSummaryMapper projectBorrowerSummaryMapper;
	
	@Autowired
	private Notifiers notifiers;
	
	@Reference(version = "1.0.0")
	private TianChengRefundEventService tianChengRefundEventService;

	@Override
	public RefundNotifyHandleResult handle(RefundNotifyDTO refundNotifyDTO) {
		RefundNotifyHandleResult refundNotifyHandleResult = null;
        try {
        	// 还款订单
            RefundOrder refundOrder = refundNotifyDTO.getRefundOrder();
			if (!isNeedPushToBorrower(refundOrder)) {
				return new RefundNotifyHandleResult();
			}
            
            // 标的信息
            Project project = refundNotifyDTO.getProject();

			// 机构标还款不通知借款人
			if (ProjectTypeEnum.ORG_SPEEDLOAN_NEW.getValue().equals(project.getType())) {
				return new RefundNotifyHandleResult();
			}
            
			RefundNotifyMessageDTO refundNotifyMessageDTO = JSONObject.parseObject(JSONObject.toJSONString(refundNotifyDTO), RefundNotifyMessageDTO.class);
			refundNotifyMessageDTO.setProjectTitle(project.getTitle());
			refundNotifyMessageDTO.setAmount(refundOrder.getAmount());
			
			// 判断是否卡牛
			boolean isCardLoan = project.getType().equals(ProjectTypeEnum.CARD_NIU_LOAN.getValue());
			boolean isFormCardNiu = project.getFromSource().equals(ProjectFromSourceEnum.CARD_NIU.getType());
			if (isCardLoan && isFormCardNiu) {
				NotifyTypeEnum notifyTypeEnum = this.getCardNiuRepaymentSuccessNotifyTypeEnum(refundNotifyDTO);
				if (notifyTypeEnum != null) {
					notifiers.notifyUser(notifyTypeEnum, refundNotifyMessageDTO);
				}
			} else {
				notifiers.notifyUser(this.getRepaymentSuccessNotifyTypeEnum(refundNotifyDTO), refundNotifyMessageDTO);
			}
			refundNotifyHandleResult = new RefundNotifyHandleResult();
        } catch (Exception e) {
        	refundNotifyHandleResult = new RefundNotifyHandleResult(e.getMessage());
			log.error("借款人-还款消息通知，异常原因：{},请求参数:{}", e.getMessage(), JSONObject.toJSONString(refundNotifyDTO.getRefundNotifyRecord()), e);
        }
        return refundNotifyHandleResult;
	}
	
	@Override
	public Object bulidParam(RefundNotifyDTO refundNotifyDTO) {
		return null;
	}	
	
	@Override
	public RefundNotifyEnum getType() {
		return RefundNotifyEnum.MESSAGE_BORROWER_REFUND;
	}	
	
	/**
	 * 获取卡牛还款通知类型
	 * 
	 * @param refundNotifyDTO
	 * @return
	 */
    private NotifyTypeEnum getCardNiuRepaymentSuccessNotifyTypeEnum(RefundNotifyDTO refundNotifyDTO){
    	Project project = refundNotifyDTO.getProject();
    	RefundOrder refundOrder = refundNotifyDTO.getRefundOrder();
    	RefundNotifyRecord refundNotifyRecord = refundNotifyDTO.getRefundNotifyRecord();
    	
    	// 提前还款
		if (refundOrder.getRefundType() == 2) {
			return NotifyTypeEnum.CARD_JS021;
		}
		// 项目完结
		ProjectBorrowerSummary projectBorrowerSummary = projectBorrowerSummaryMapper.selectByPrimaryKey(project.getProjectId());
		if (refundNotifyRecord.getCurrentPeriod() == projectBorrowerSummary.getTotalPeriod().intValue()
				&& RepayStatusEnum.SETTLEMENT.getCode().equals(projectBorrowerSummary.getRepayStatus())) {
            return NotifyTypeEnum.CARD_JS018;
        }
        return null;
    }	
    
    /**
     * 获取极速借还款通知类型
     * 
     * @param batchTransOrder
     * @return
     */
    private NotifyTypeEnum getRepaymentSuccessNotifyTypeEnum(RefundNotifyDTO refundNotifyDTO){
    	Project project = refundNotifyDTO.getProject();
    	RefundOrder refundOrder = refundNotifyDTO.getRefundOrder();
    	RefundNotifyRecord refundNotifyRecord = refundNotifyDTO.getRefundNotifyRecord();
    	
    	// 提前还款
		if (refundOrder.getRefundType() == 2) {
			return NotifyTypeEnum.JS021;
		}
		
		// 项目完结
		ProjectBorrowerSummary projectBorrowerSummary = projectBorrowerSummaryMapper.selectByPrimaryKey(project.getProjectId());
		if (refundNotifyRecord.getCurrentPeriod() == projectBorrowerSummary.getTotalPeriod().intValue()
				&& RepayStatusEnum.SETTLEMENT.getCode().equals(projectBorrowerSummary.getRepayStatus())) {
            return NotifyTypeEnum.JS018;
        }
		
		// 普通还款
        return NotifyTypeEnum.JS017;
    }	
	
	/**
	 * 是否需要发送给借款人
	 * 
	 * @param refundOrder
	 * @return
	 */
	private boolean isNeedPushToBorrower(RefundOrder refundOrder) {
		if (refundOrder == null 
				|| !RefundTradeTypeEnum.REPAYMENT.getTradeType().equals(refundOrder.getTradeType())
				|| !RefundOrderStatusEnum.HANDLED.getCode().equals(refundOrder.getStatus())
				|| BigDecimal.ZERO.compareTo(refundOrder.getAmount()) >= 0) {
			return false;
		}
        return true;
    }
}